<template>
  <el-container style="position: relative">
    <SiteTree style="position: fixed" @on-choose-region="filetrStation" />
    <el-main class="SubItemAnalysisContent">
      <el-card class="lg-mb-20">
        <div
          class="default-main"
          style="
            display: flex;
            justify-content: flex-start;
            align-items: center;
          "
        >
          <!-- 表格与图表切换 -->
          <el-radio-group v-model="radio1" @change="changeDiffWayShowData">
            <el-radio label="数据" border>数据</el-radio>
            <el-radio label="图表" border>图表</el-radio>
          </el-radio-group>
          <!-- 时间选择 -->
          <div style="margin-left: 2%">
            <el-date-picker
              style="width: 150px"
              v-model="qoqStore.date"
              :type="state.dateType"
              :disabled-date="pickerOptions"
              placeholder="选择日期"
              @change="dateChange"
              :format="state.format"
              :value-format="state.format"
            />
          </div>
          <div class="btn" style="margin-left: 2%">
            <el-button @click="prev">上一{{ state.btnUnit }}</el-button>
            <el-button @click="next" :disabled="state.disabled"
              >下一{{ state.btnUnit }}
            </el-button>
          </div>
          <!-- 年月日报 -->
          <div class="report" style="margin-left: 2%">
            <el-select
              v-model="option"
              clearable
              @change="ReportChange"
              style="width: 150px"
            >
              <el-option
                v-for="(item, index) in state.report"
                :key="index"
                :label="item"
                :value="item"
              />
            </el-select>
          </div>
        </div>
        <QOQ ref="QOQRef" v-if="state.show" />
        <!-- 图表数据 -->
        <Echarts
          ref="EchartsRef"
          v-if="state.EchartsShow"
          v-model="state.unit"
        />
        <div v-else>请选择左侧站点</div>
      </el-card>
    </el-main>
  </el-container>
</template>
<script lang="ts" setup>
import {
  reactive,
  onMounted,
  provide,
  ref,
  onBeforeUnmount,
  computed,
} from "vue";
import SiteTree from "./components/aside.vue";
import { useConfig } from "@/store/config"; //后台布局相关仓库
import { useDictionary } from "@/store/backend/tool/dictionary";
import { useAssetSite } from "@/store/backend/Assets/site";
import { useWarningItemObject } from "@/store/backend/Warning/itemObject";
import { timeFormat, TimeOfPeriod } from "@/utils/common"; // 导入表格api方法生成器
import { useAssetCabinet } from "@/store/backend/Assets/cabinet";
import { useElectricData } from "@/store/backend/DataM/RealTime";
import { useElectricSubitemByDay } from "@/store/backend/DataM/SubitemByDay";
import QOQ from "./components/qoq.vue";
import { useAssetElectric } from "@/store/backend/Assets/electric";
import { useElectricYearAnalysis } from "@/store/backend/DataM/YearAnalysis";
import { useElectricRingAnalysis } from "@/store/backend/DataM/RingAnalysis";
import Echarts from "./components/echarts.vue";

const dictionary = useDictionary();
const config = useConfig();
const site = useAssetSite();
const itemObject = useWarningItemObject();
const cabinet = useAssetCabinet();
const realTime = useElectricData();
const analysis = useElectricSubitemByDay();
const electric = useAssetElectric();
const yoyStore = useElectricYearAnalysis(); //同比
const qoqStore = useElectricRingAnalysis(); //环比
const QOQRef = ref();

const option = ref("日");
const radio1 = ref("数据");

const timeOfPeriod = new TimeOfPeriod();
class newTimeOfPeriod extends TimeOfPeriod {
  getEnd() {
    let date = new Date();
    date.setMonth(date.getMonth() + 1);
    date.setDate(0);
    // let lastDay = date.toLocaleDateString().replace(/\//g, "-");
    let lastDay =
      date.getFullYear() +
      "-" +
      JSON.stringify(date.getMonth() + 1).padStart(2, "0") +
      "-" +
      JSON.stringify(date.getDate()).padStart(2, "0");
    lastDay = lastDay;
    console.log("前月的最后一天", lastDay);
    return lastDay;
  }
}
const newTime = new newTimeOfPeriod();

const state: {
  show: boolean;
  EchartsShow: boolean;
  isOpen: boolean;
  disabled: boolean;
  stateTime: any;
  searchForm: any;
  lastData: any[];
  btnUnit: any;
  report: any;
  timeFiled: number;
  today: any;
  dateType: any;
  format: any;
  unit: any;
} = reactive({
  show: false,
  EchartsShow: false,
  isOpen: false,
  disabled: true,
  timeFiled: 24,
  stateTime: "",
  today: "",
  lastData: [],
  dateType: "date",
  format: "YYYY-MM-DD",
  btnUnit: "日",
  report: ["日", "月", "年"],
  unit: "时",
  searchForm: {
    ecode: "", //电表号
    siteids: [],
    start: 0,
    end: 23,
    date: "",
  },
});

//日月年报告
const ReportChange = (val: any) => {
  state.btnUnit = val;
  switch (val) {
    case "日":
      state.unit = "时"; //单位
      qoqStore.unit = "时";
      state.dateType = "date";
      state.format = "YYYY-MM-DD";
      state.searchForm.start = 0;
      state.searchForm.end = 23;
      qoqStore.start = state.searchForm.start;
      qoqStore.end = state.searchForm.end;
      qoqStore.date = timeFormat("", "yyyy-mm-dd");
      state.stateTime = qoqStore.date;
      state.today = qoqStore.date;
      state.timeFiled = 24;
      refreshData();
      break;
    case "月":
      state.unit = "日"; //单位
      qoqStore.unit = "日";
      state.dateType = "month";
      state.format = "YYYY-MM";
      state.searchForm.start = 1;
      state.searchForm.end = newTime.getEnd().split("-")[2];
      qoqStore.start = state.searchForm.start;
      qoqStore.end = state.searchForm.end;
      qoqStore.date = timeFormat("", "yyyy-mm");
      state.stateTime = qoqStore.date;
      state.today = qoqStore.date;
      state.timeFiled = 32;
      refreshData();
      break;
    case "年":
      state.unit = "月"; //单位
      qoqStore.unit = "月";
      state.dateType = "year";
      state.format = "YYYY";
      state.searchForm.start = 1;
      state.searchForm.end = 12;
      qoqStore.start = state.searchForm.start;
      qoqStore.end = state.searchForm.end;
      qoqStore.date = timeFormat("", "yyyy");
      state.stateTime = qoqStore.date;
      state.today = qoqStore.date;
      state.timeFiled = 13;
      refreshData();
      break;
  }
};

//限制用户选择日期
const pickerOptions = (time: Date) => {
  return time.getTime() > Date.now();
};

//刷新
const refreshData = () => {
  analysis.filedArr = []; //表格重组字段刷新
  if (state.isOpen && state.show && radio1.value === "数据") {
    state.show = false;
    setTimeout(() => {
      state.show = true;
    }, 500);
  } else if (state.isOpen && state.EchartsShow && radio1.value === "图表") {
    state.EchartsShow = false;
    setTimeout(() => {
      state.EchartsShow = true;
    }, 500);
  } else {
    if (radio1.value === "数据") {
      state.show = true;
      state.EchartsShow = false;
    }
    if (radio1.value === "图表") {
      state.show = false;
      state.EchartsShow = true;
    }
    state.isOpen = true;
  }
};
//接收站点树传递过来的数据
const filetrStation = (row: any, node: any) => {
  console.log("接收站点树传递过来的数据", row, node);
  if (row && node) {
    qoqStore.siteids = node.checkedKeys;
  }
  if (!node) {
    qoqStore.siteids = row;
  }
  refreshData();
};

//选择不同方法展示数据
const changeDiffWayShowData = (value: any) => {
  console.log("选择不同方法展示数据", value);
  if (state.isOpen && value === "图表") {
    state.show = false;
    state.EchartsShow = true;
  }
  if (state.isOpen && value === "数据") {
    state.show = true;
    state.EchartsShow = false;
  }
};

//年份选择
const dateChange = (val: any) => {
  state.stateTime = val
    ? val + "-" + timeFormat("", "mm-dd")
    : timeFormat("", "yyyy-mm-dd");
  qoqStore.date = state.stateTime;
  refreshData();
  isDisabled();
};

//判断月有多少天
const getCountDays = (year: any, month: any) => {
  //month是字符串类型需要进行类型转换;
  switch (Number(month)) {
    case 1:
    case 3:
    case 5:
    case 7:
    case 8:
    case 10:
    case 12:
      return 31;
    case 4:
    case 6:
    case 9:
    case 11:
      return 30;
    case 2:
      //2月要考虑闰年
      if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
        return 29;
      } else {
        return 28;
      }
  }
};
//判断日月年不同附加数据 上一月加天数与下一月加天数计算的月份天数需判断
const diffData = (num: any) => {
  let timeStamp: any = "";
  let formatParams: any = "";
  let params = state.stateTime.split("-");
  if (state.btnUnit === "日") {
    timeStamp = 1 * 24 * 60 * 60 * 1000;
    formatParams = "yyyy-mm-dd";
  }
  if (state.btnUnit === "月") {
    let days = getCountDays(params[0] - 0, params[1] - num);
    timeStamp = 1 * 24 * 60 * 60 * 1000 * (days as any);
    formatParams = "yyyy-mm";
  }
  if (state.btnUnit === "年") {
    timeStamp = 1 * 24 * 60 * 60 * 1000 * 365;
    formatParams = "yyyy";
  }
  return { timeStamp, formatParams };
};
//上一 日月年
const prev = () => {
  let obj: any = diffData(1);
  qoqStore.date = timeFormat(
    Math.floor(Date.parse(state.stateTime) - obj.timeStamp),
    obj.formatParams
  );
  state.stateTime = qoqStore.date;
  isDisabled();
};
//下一 日月年
const next = () => {
  let obj: any = diffData(0);
  qoqStore.date = timeFormat(
    Math.floor(Date.parse(state.stateTime) + obj.timeStamp),
    obj.formatParams
  );

  state.stateTime = qoqStore.date;
  isDisabled();
};

//判断下一按钮是否可以点击
const isDisabled = () => {
  if (state.isOpen) {
    refreshData();
  }
  if (
    state.btnUnit === "日" &&
    state.stateTime !== timeFormat("", "yyyy-mm-dd") &&
    Math.floor(Date.parse(state.stateTime)) <
      Math.floor(Date.parse(timeFormat("", "yyyy-mm-dd")))
  ) {
    state.disabled = false;
  } else if (
    state.btnUnit === "月" &&
    state.stateTime !== timeFormat("", "yyyy-mm") &&
    Math.floor(Date.parse(state.stateTime)) <
      Math.floor(Date.parse(timeFormat("", "yyyy-mm")))
  ) {
    state.disabled = false;
  } else if (
    state.btnUnit === "年" &&
    state.stateTime !== timeFormat("", "yyyy") &&
    Math.floor(Date.parse(state.stateTime)) <
      Math.floor(Date.parse(timeFormat("", "yyyy")))
  ) {
    state.disabled = false;
  } else {
    state.disabled = true;
  }
};
// 获取当前时间;
const getTime = () => {
  state.stateTime = timeFormat("", "yyyy-mm-dd");
  qoqStore.date = state.stateTime;
};
getTime();

const menuWidth = computed(() => config.overviewMenuWidth());

onMounted(() => {});

provide("site", site);
provide("config", config);
provide("dictionary", dictionary);
provide("realTime", realTime);
provide("itemObject", itemObject);
provide("cabinet", cabinet);
provide("analysis", analysis);
provide("electric", electric);
provide("yoyStore", yoyStore);
provide("qoqStore", qoqStore);

onBeforeUnmount(() => {
  qoqStore.date = "";
  qoqStore.ecode = "";
});
</script>
<style lang="scss" scoped>
.default-main {
  margin: var(--ba-main-space) var(--ba-main-space) 20px var(--ba-main-space);
}
.SubItemAnalysisContent {
  margin-left: v-bind(menuWidth);
}
</style>
